package com.yaolaizaixian.merchant.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.victor.loading.rotate.RotateLoading;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.adapter.FragmentSalesShopAdapter;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.SalesShopData;
import com.yaolaizaixian.merchant.bean.SalesShopModel;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/2/23.
 * <p/>
 * 销售记录列表
 */
public class SalesRecordActivity extends BaseActivity {


    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.tv_salesrecord_week)
    TextView tvSalesrecordWeek;
    @BindView(R.id.rl_salesrecord_week)
    AutoRelativeLayout rlSalesrecordWeek;
    @BindView(R.id.tv_salesrecord_month)
    TextView tvSalesrecordMonth;
    @BindView(R.id.rl_salesrecord_month)
    AutoRelativeLayout rlSalesrecordMonth;
    @BindView(R.id.ll_salesrecord_twotitle)
    AutoLinearLayout llSalesrecordTwotitle;
    @BindView(R.id.tv_orderlist_bulu)
    TextView tvOrderlistBulu;
    @BindView(R.id.iv_orderlist2)
    ImageView ivOrderlist2;
    @BindView(R.id.rl_select_month)
    AutoRelativeLayout rlSelectMonth;
    @BindView(R.id.xrv_salelist)
    XRecyclerView xrvSalelist;
    @BindView(R.id.iv_kong)
    ImageView ivKong;
    @BindView(R.id.rl_kong)
    AutoRelativeLayout rlKong;
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;

    private String TAG = "SalesRecordActivity";

    private int pageNum = 1;
    private String userId;

    private FragmentSalesShopAdapter fragmentSalesShopAdapter;
    private List<SalesShopData> totalSales;
    private TimePickerView pvTime;
    //日期
    private String date = "";
    //    （week：周排行，month：月排行）
    private String type = "week";

    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;
                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);
                    if (baseModel.isFlag()) {

                        final SalesShopModel salesShopModel = GsonUtil.jsonToBean(result, SalesShopModel.class);
                        salesShopDatas = salesShopModel.getData();

                        if (null != salesShopDatas && salesShopDatas.size() > 0) {

                            if (pageNum == 1) {

                                totalSales.clear();
                                totalSales.addAll(salesShopDatas);

                            } else {

                                totalSales.addAll(salesShopDatas);
                            }


                        }
                        if (totalSales.size() <= 0) {

                            rlKong.setVisibility(View.VISIBLE);

                        }

                        if (null == fragmentSalesShopAdapter) {

                            fragmentSalesShopAdapter = new FragmentSalesShopAdapter(SalesRecordActivity.this, totalSales);

                            xrvSalelist.setAdapter(fragmentSalesShopAdapter);

                        } else {

                            fragmentSalesShopAdapter.notifyDataSetChanged();

                        }
                        if (pageNum == 1) {

                            xrvSalelist.refreshComplete();

                        } else {

                            xrvSalelist.loadMoreComplete();
                        }
                        dissmiss();

                    } else {

                        dissmiss();

                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {
                            showConflictDialog(SalesRecordActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(SalesRecordActivity.this, "您的账号在其它设备登录");

                        } else {
                            rlKong.setVisibility(View.VISIBLE);
                            Toast.makeText(SalesRecordActivity.this, baseModel.getErrorMsg(), Toast.LENGTH_SHORT);
                            return;
                        }

                    }
                    break;


            }
        }
    };
    private int year;
    private int month;
    private int day;
    private List<SalesShopData> salesShopDatas;
    private String months;
    private String days;

    @Override
    public void initView() {

        setContentView(R.layout.activity_salesrecord);
        totalSales = new ArrayList<>();
    }

    @Override
    public void initData() {
        tvTitleText.setText("销售排行");
        LinearLayoutManager layoutManager = new LinearLayoutManager(SalesRecordActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xrvSalelist.setLayoutManager(layoutManager);
        xrvSalelist.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xrvSalelist.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        xrvSalelist.setArrowImageView(R.mipmap.iconfont_downgrey);

        //获取系统日期
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        day = c.get(Calendar.DAY_OF_MONTH);

        //周日期
        if (month < 10) {
            months = "-0" + month;
        } else {
            months = "-" + month;
        }
        if (day < 10) {
            days = "-0" + day;
        } else {
            days = "-" + day;
        }
        tvOrderlistBulu.setText(year+"年"+month+"月");

        //时间选择器
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year, c.get(Calendar.MONTH), day);


        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date dates, View v) {//选中事件回调
                tvOrderlistBulu.setText(getTime2(dates));
                date=getTime(dates);
                setselect();

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择日期")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();

        //用户id
        userId = SharedPreferencesUtil.getString(getApplicationContext(), "usersysno", "");

        //上拉刷新
        xrvSalelist.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum = 1;
                        getData(pageNum + "", type, date);


                    }

                }, 1000);

            }

            //加载更多
            @Override
            public void onLoadMore() {

                new Handler().postDelayed(new Runnable() {
                    public void run() {

                        pageNum += 1;
                        getData(pageNum + "", type, date);

                    }
                }, 1000);


            }
        });


        date = year + months + days;
        showloading();
        getData(pageNum + "", type, date);


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_back, R.id.rl_salesrecord_week, R.id.rl_salesrecord_month, R.id.rl_select_month})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:

                finish();

                break;
            case R.id.rl_salesrecord_week:

                //本周
                cleanview();
                rlSalesrecordWeek.setBackgroundColor(getResources().getColor(R.color.pink));
                type = "week";
                date = year + months + days;
                rlSelectMonth.setVisibility(View.GONE);
                setselect();

                break;
            case R.id.rl_salesrecord_month:

                //本月
                cleanview();
                rlSalesrecordMonth.setBackgroundColor(getResources().getColor(R.color.pink));
                type = "month";
                date = year + months;
                rlSelectMonth.setVisibility(View.VISIBLE);
                setselect();


                break;
            case R.id.rl_select_month:

                pvTime.show();

                break;

        }
    }

    private void cleanview() {
        rlSalesrecordWeek.setBackgroundColor(getResources().getColor(R.color.backtwo));
        rlSalesrecordMonth.setBackgroundColor(getResources().getColor(R.color.backtwo));
    }

    private void setselect() {

        pageNum = 1;

        showloading();

        //隐藏空数据
        rlKong.setVisibility(View.GONE);

        if (null != totalSales && totalSales.size() > 0) {
            totalSales.clear();
            salesShopDatas.clear();
            //获取数据
            getData(pageNum + "", type, date);
            fragmentSalesShopAdapter.notifyDataSetChanged();

        } else {

            //获取数据
            getData(pageNum + "", type, date);
        }

    }

    /**
     * 获取排行
     * * userId		用户ID
     * pageNum	页码
     * pageSize
     */
    private void getData(String pageNum, String type, String date) {
        //店铺id
        String shopsysno = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");
        try {

            HashMap<String, String> sortedParams = new HashMap<String, String>();
            // sysNo 值  3des加密
            String url = BaseInfo.URL + "lifeOrder/getLifeRankingSalesList.do";
            sortedParams.put("pageSize", "10");
            sortedParams.put("pageNum", pageNum);
            sortedParams.put("userId", userId);
            sortedParams.put("type", type);
            sortedParams.put("date", date);
            sortedParams.put("shopSysno", shopsysno);

            OkHttpUtils
                    .post()
                    .url(url)
                    .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                    .build()
                    .execute(new MyStringCallback());

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            dissmiss();
            rlKong.setVisibility(View.VISIBLE);

        }

        @Override
        public void onResponse(String response, int id) {
            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }

    private void dissmiss() {

        if (rotateloading.isStart()) {

            rotateloading.stop();
        }

    }

    private void showloading() {

        rotateloading = (RotateLoading) findViewById(R.id.rotateloading);

        rotateloading.start();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(date);
    }
    private String getTime2(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }
}
